package com.menhai.personmanagement.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.menhai.personmanagement.entity.Codelist;
import com.menhai.personmanagement.entity.User;
import com.menhai.personmanagement.entity.co.UserCo;
import com.menhai.personmanagement.entity.vo.UserVo;
import com.menhai.personmanagement.plus.DateUtils;
import com.menhai.personmanagement.plus.OperLog;
import com.menhai.personmanagement.plus.Uuid;
import com.menhai.personmanagement.services.ICodelistService;
import com.menhai.personmanagement.services.UserService;
import com.menhai.personmanagement.utils.ExportSysUserInfoExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.menhai.personmanagement.utils.ExcelOperUtil.addSelect;
import static com.menhai.personmanagement.utils.ExcelOperUtil.codesString;

@Slf4j
@RestController
public class UserConntroller {

    @Autowired
    private  UserService userService;

    @Autowired
    private ICodelistService codelistService;

    @RequestMapping("/login")
    public List<User> login(@Param("mobile") String mobile,@Param("password") String password){
        List<User> list = userService.login(mobile,password);
        return list;
    }

    /**
     * @describe 医生列表
     * @param user
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.menhai.personmanagement.entity.User>
     * @Date 2021/12/2 13:36
     * @author shikun
     */
    @OperLog(operDesc = "查询医生",operType = "查询")
    @RequestMapping("/selectByList")
    public IPage<User> selectByList(UserCo user){
        IPage<User> list = userService.selectByList(user);
        return list;
    }

    /**
     * @describe 医生列表不查找已经停用得
     * @param user
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.menhai.personmanagement.entity.User>
     * @Date 2021/12/22 16:07
     * @author shikun
     */
    @RequestMapping("/selectByisAvailable")
    public IPage<User> selectByisAvailable(UserCo user){
        IPage<User> list = userService.selectByisAvailable(user);
        return list;
    }

    /**
     * @describe 根据工号查询医生
     * @param user
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.menhai.personmanagement.entity.User>
     * @Date 2022/1/18 13:39
     * @author shikun
     */
    @RequestMapping("/selectByjobnumber")
    public List<User> selectByjobnumber(User user){
        List<User> list = userService.selectByjobnumber(user);
        return list;
    }

   /**
    * @describe 医生导出
    * @param user
    * @Return java.util.List<com.menhai.personmanagement.entity.vo.UserVo>
    * @Date 2021/12/15 10:32
    * @author shikun
    */
    @RequestMapping("/selectByListExport")
    public List<UserVo> selectByListExport(UserCo user){
        List<UserVo> list = userService.selectByListExport(user);
        return list;
    }

    /**
     * @describe 添加医生
     * @param userVo
     * @Return int
     * @Date 2021/12/2 13:37
     * @author shikun
     */
    @OperLog(operDesc = "添加医生",operType = "插入")
    @RequestMapping("/saveAddUser")
    public int saveAddUser(@RequestBody UserVo userVo){
        int flag =  userService.saveAddUser(userVo);
        return flag;
    }

    /**
     * @describe 审核医生
     * @param user
     * @Return int
     * @Date 2022/1/19 14:03
     * @author shikun
     */
    @RequestMapping("/auditdoctor")
    public int auditdoctor(User user){
        int flag =  userService.auditdoctor(user);
        return flag;
    }

    /**
     * @describe 驳回医生
     * @param user
     * @Return int
     * @Date 2022/1/19 15:48
     * @author shikun
     */
    @RequestMapping("/turndown")
    public int turndown(User user){
        int flag =  userService.turndown(user);
        return flag;
    }

    /**
     * @describe 删除医生
     * @param user
     * @Return int
     * @Date 2021/12/2 13:37
     * @author shikun
     */
    @RequestMapping("/saveDeleteUser")
    public int deleteById(User user){
        int flag =  userService.deleteById(user);
        return flag;
    }

    /**
     * @describe 停用医生
     * @param user
     * @Return int
     * @Date 2021/12/22 14:16
     * @author shikun
     */
    @OperLog(operDesc = "停用,启用医生",operType = "修改")
    @RequestMapping("/upoByIdisAvailable")
    public int upoByIdisAvailable(User user){
        int flag =  userService.upoByIdisAvailable(user);
        return flag;
    }


    /**
     * @describe 根据id 查询医生
     * @param user
     * @Return com.menhai.personmanagement.entity.User
     * @Date 2021/12/2 14:01
     * @author shikun
     */
    @OperLog(operDesc = "根据医生ID查询医生",operType = "查询")
    @RequestMapping("/selectById")
    public UserVo selectById(User user){
        return userService.selectById(user);
    }


    /**
     * @describe 修改医生实体
     * @param userCo
     * @Return int
     * @Date 2021/12/3 16:37
     * @author shikun
     */
    @OperLog(operDesc = "修改医生信息",operType = "修改")
    @PostMapping("/updateById")
    public int updateById(@RequestBody UserCo userCo){
        return  userService.updateById(userCo);
    }


    public List<User> importData(MultipartFile file) throws IOException{
        List<User> data = new ArrayList();
        ExcelUtil.readBySax(file.getInputStream(),-1,new RowHandler() {
            @Override
            public void handle(int i, long l, List<Object> list) {
                list.removeAll(Collections.singleton(null));
                if(l > 0){
                    User user = new User();
                    user.setName(list.get(0).toString());
                    user.setAge(list.get(1).toString());
                    user.setSex(list.get(2).toString());
                    user.setJobnumber(list.get(3).toString());
                    user.setIdentity(list.get(4).toString());
                    user.setClassid(list.get(5).toString());
                    user.setPositionid(list.get(6).toString());
                    user.setMobile(list.get(7).toString());
                    user.setAddress(list.get(8).toString());
                    user.setMarriage(list.get(9).toString());
                    user.setPoliticsface(list.get(10).toString());
                    user.setEduid(list.get(11).toString());//县
                    if(list.size()>12)
                    user.setAccount(list.get(12).toString());//镇
                    if(list.size()>13)
                    user.setPassword(list.get(13).toString());//村
                    data.add(user);
                }
            }
        });
        return data;
    }

    /**
     * @describe 导入医生数据
     * @param file
     * @Return int
     * @Date 2021/11/30 10:06
     * @author shikun
     */
    @OperLog(operDesc = "导入医生",operType = "插入")
    @RequestMapping("/excelImport")
    public String uploadImg(@RequestParam("file") MultipartFile file ,@Param("id") String  id) {
        if (file.isEmpty()) {
            return "失败";
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //人员集合
        List<User> excels = null;
        try {
            excels = importData(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ;
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        List<Codelist> positionlist = codelistService.selectByCodeKindCode("POSITIONID");

        List<Codelist> classlist = codelistService.selectByCodeKindCode("CLASSID");

        List<Codelist> marriagelist = codelistService.selectByCodeKindCode("MARRIAGE");

        List<Codelist> politicsfacelist = codelistService.selectByCodeKindCode("POLITICSFACE");

        List<Codelist> sexlist = codelistService.selectByCodeKindCode("SEX");

        //县
        List<Codelist> xianlist =  codelistService.getHospital();

        //镇
        List<Codelist> zhenlist =  codelistService.getZhenHospital();

        //村
        List<Codelist> chunlist =  codelistService.getChunHospital();

        for (User user : excels){
            user.setId(new Uuid().getUUId());
            user.setCtime(DateUtils.getLocalTime());
            user.setIsAvailable("1");
            user.setAudit("0");
            for (Codelist sexL : sexlist){
                if(user.getSex().equals(sexL.getCodeName())){
                    user.setSex(sexL.getCodeValue());
                }
            }
            for (Codelist classL : classlist){
                if(user.getClassid().equals(classL.getCodeName())){
                    user.setClassid(classL.getCodeValue());
                }
            }
            for (Codelist positionL : positionlist){
                if(user.getPositionid().equals(positionL.getCodeName())){
                    user.setPositionid(positionL.getCodeValue());
                }
            }
            for (Codelist marriagL : marriagelist){
                if(user.getMarriage().equals(marriagL.getCodeName())){
                    user.setManageid(marriagL.getCodeValue());
                }
            }
            for (Codelist politicsfaceL : politicsfacelist){
                if(user.getPoliticsface().equals(politicsfaceL.getCodeName())){
                    user.setPoliticsface(politicsfaceL.getCodeValue());
                }
            }
            for (Codelist xian : xianlist){
                if(user.getEduid().equals(xian.getCodeName())){
                    user.setSuperiorName(xian.getCodeValue());
                    user.setSuperiorCode(xian.getCodeValue());
                    user.setEduid("");
                }
            }
            for (Codelist zhen : zhenlist){
                if(user.getAccount()!=null && user.getAccount().equals(zhen.getCodeName())){
                    user.setSuperiorName(user.getSuperiorName()+","+zhen.getCodeValue());
                    user.setSuperiorCode(zhen.getCodeValue());
                    user.setAccount("");
                }
            }
            for (Codelist chun : chunlist){
                if(user.getPassword()!=null &&  user.getPassword().equals(chun.getCodeName())){
                    user.setSuperiorName(user.getSuperiorName()+","+chun.getCodeValue());
                    user.setSuperiorCode(chun.getCodeValue());
                    user.setPassword("");
                }
            }
            try
            {
                if(user.getSuperiorCode()==null){
                    int a = 1/0;
                }else{

//                   String [] array = user.getSuperiorName().split(",");
//
//                    if(array.length==3){
//                        user.setSuperiorName(array[2].substring(0,4)+","+array[2].substring(0,6)+","+array[2]);
//                    }
//                    if(array.length==2){
//                        user.setSuperiorName(array[1].substring(0,4)+","+array[1]);
//                    }
//                    if(array.length==1){
//                        if(array[0].length()==6){
//                            user.setSuperiorName(array[0].substring(0,4)+","+array[0]);
//                        }
//                        if(array[0].length()==8){
//                            user.setSuperiorName(array[0].substring(0,4)+","+array[0].substring(0,6)+","+array[0]);
//                        }
//                    }

                    List<User>  userList =userService.selectByjobnumber(user);
                    if(userList.size()>0){
                        int a = 1/0;
                    }else{
                        int result = userService.insertUserlist(user);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、姓名 " + user.getName() + " 导入成功");
                    }
                }
            }
            catch (Exception e)
            {
                failureNum++;
                successMsg.append("<br/>" + failureNum + "、姓名 " + user.getName() + " 导入失败");
            }
        }
        if (failureNum > 0)
        {
            successMsg.insert(0, "很抱歉，导入失败！共 " + failureNum);
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }

   /**
    * @describe 导出数据 医生信息
    * @param
    * @Return void
    * @Date 2021/11/30 10:41
    * @author shikun
    */
   @OperLog(operDesc = "导出医生信息",operType = "导出")
    @RequestMapping("/export")
    public void export(HttpServletResponse response,UserCo userCo){
        try {
            List<UserVo> list = userService.selectByListExport(userCo);
            ServletOutputStream out = response.getOutputStream();
            new ExportSysUserInfoExcel().export(list, out, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @describe 医生模板
     * @param response
     * @Return void
     * @Date 2021/12/20 15:13
     * @author shikun
     */
    @OperLog(operDesc = "下载医生导入模板",operType = "导出")
    @RequestMapping("/getImportPopulationTemplate")
    public void getImportPopulationTemplate(HttpServletResponse response){
        //职务
        List<Codelist> positionlist = codelistService.selectByCodeKindCode("POSITIONID");
        String[] positions = codesString(positionlist);
        //科室
        List<Codelist> classlist = codelistService.selectByCodeKindCode("CLASSID");
        String[] classs = codesString(classlist);
        //婚姻状况
        List<Codelist> marriagelist = codelistService.selectByCodeKindCode("MARRIAGE");
        String[] marriages = codesString(marriagelist);
        //政治面貌
        List<Codelist> politicsfacelist = codelistService.selectByCodeKindCode("POLITICSFACE");
        String[] politicsfaces = codesString(politicsfacelist);
        //性别
        List<Codelist> sexlist = codelistService.selectByCodeKindCode("SEX");
        String[] sexs = codesString(sexlist);
        //县
        List<Codelist> xianlist =  codelistService.getHospital();
        String[] xians = codesString(xianlist);
        //镇
        List<Codelist> zhenlist =  codelistService.getZhenHospital();
        String[] zhens = codesString(zhenlist);
        //村
        List<Codelist> chunlist =  codelistService.getChunHospital();
        String[] chuns = codesString(chunlist);

        ExcelWriter writer = ExcelUtil.getWriter();
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("age", "年龄");
        writer.addHeaderAlias("sex", "性别");
        writer.addValidationData(addSelect(writer,sexs,1,2));
        writer.addHeaderAlias("jobnumber", "工号");
        writer.addHeaderAlias("identity", "身份证");
        writer.addHeaderAlias("classid", "科室");
        writer.addValidationData(addSelect(writer,classs,1,5));
        writer.addHeaderAlias("positionid", "职务");
        writer.addValidationData(addSelect(writer,positions,1,6));
        writer.addHeaderAlias("mobile", "联系方式");
        writer.addHeaderAlias("address", "家庭住址");
        writer.addHeaderAlias("marriage", "婚姻状况");
        writer.addValidationData(addSelect(writer,marriages,1,9));
        writer.addHeaderAlias("politicsface", "政治面貌");
        writer.addValidationData(addSelect(writer,politicsfaces,1,10));
        writer.addHeaderAlias("eduid", "所属一级");
        writer.addValidationData(addSelect(writer,xians,1,11));
        writer.addHeaderAlias("account", "所属二级");
        writer.addValidationData(addSelect(writer,zhens,1,12));
        writer.addHeaderAlias("password", "所属三级");
        writer.addValidationData(addSelect(writer,chuns,1,13));
        List list = new ArrayList();
        list.add(new User());
        writer.setOnlyAlias(true);
        writer.write(list,true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = new String("信息模板".getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
        IoUtil.close(out);
    }
}
